﻿Public Class MainForm
   Const SCRIPT_NAME As String = "EasyConv Script.bat"
   Const CLI_NAME As String = "HandBrakeCLI.exe"
   Const TOPMOST_OPACITY As Single = 0.7

   Public Class Job
      Public Sub New(ByVal path As String)
         Me.Path = path
      End Sub

      Public Path As String

      Public Overrides Function ToString() As String
         Return IO.Path.GetFileName(Path)
      End Function

      Public Overrides Function Equals(ByVal obj As Object) As Boolean
         If TypeOf obj Is Job Then
            Return Path.Equals(CType(obj, Job).Path)
         End If
         Return MyBase.Equals(obj)
      End Function
   End Class

   Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
      FolderBrowserDialog.SelectedPath = My.Settings("target")

      If FolderBrowserDialog.ShowDialog <> Windows.Forms.DialogResult.OK Then
         Return
      End If

      My.Settings("target") = FolderBrowserDialog.SelectedPath

      Me.Visible = False

      Try
         Process(FolderBrowserDialog.SelectedPath, txtCustom.Text)

         Me.Close()
      Catch ex As Exception
         MessageBox.Show(ex.Message, "Error processing script", MessageBoxButtons.OK, MessageBoxIcon.Error)
      End Try
   End Sub

   Public Sub Process(ByVal target As String, ByVal params As String)
      Dim script As String = IO.Path.Combine(IO.Path.GetTempPath, SCRIPT_NAME)
      Dim cli As String = IO.Path.Combine(IO.Path.GetDirectoryName(Reflection.Assembly.GetEntryAssembly.Location), CLI_NAME)

      If Not IO.File.Exists(cli) Then
         MessageBox.Show(CLI_NAME & " not present at " & cli, "CLI missing", MessageBoxButtons.OK, MessageBoxIcon.Error)
         Return
      End If

      'Dim content As String = ""
      For Each j As Job In lstFiles.Items
         'Dim cmd As String
         'cmd = """" & cli & """ " & String.Format(params, j.Path, IO.Path.Combine(target, IO.Path.GetFileNameWithoutExtension(j.Path)))

         Dim p As Diagnostics.Process = Diagnostics.Process.Start(cli, String.Format(params, j.Path, IO.Path.Combine(target, IO.Path.GetFileNameWithoutExtension(j.Path))))
         p.WaitForExit()

         'content &= cmd & Environment.NewLine & Environment.NewLine
      Next
      lstFiles.Items.Clear()
      btnStart.Enabled = False
      'IO.File.WriteAllText(script, content)
      'Diagnostics.Process.Start(script)
   End Sub

#Region " Dragging and scanning "

   Private Sub MainForm_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragEnter
      If e.Data.GetDataPresent(DataFormats.FileDrop) Then
         Dim bFound As Boolean
         For Each f As Object In CType(e.Data.GetData(DataFormats.FileDrop), Array)
            bFound = bFound Or HasFiles(f.ToString)
         Next
         If bFound Then
            e.Effect = DragDropEffects.Copy
         Else
            e.Effect = DragDropEffects.None
         End If
         lblSupportedTypes.Visible = Not bFound
         lstFiles.Visible = bFound
      End If
      If Me.TopMost Then
         Me.Opacity = 1
      End If
   End Sub

   Private Sub MainForm_DragLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.DragLeave
      If Me.TopMost Then
         Me.Opacity = TOPMOST_OPACITY
      End If
      lblSupportedTypes.Visible = False
      lstFiles.Visible = True
   End Sub

   Private Sub MainForm_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop
      Try
         For Each f As Object In CType(e.Data.GetData(DataFormats.FileDrop), Array)
            ScanPath(f.ToString)
         Next
      Catch ex As Exception
         MessageBox.Show("Error doing Drag/Drop")
      End Try
      If Me.TopMost Then
         Me.Opacity = TOPMOST_OPACITY
      End If
      btnStart.Enabled = lstFiles.Items.Count > 0
      lblSupportedTypes.Visible = False
      lstFiles.Visible = True
   End Sub

   Public Sub ScanPath(ByVal str As String)
      If IO.Directory.Exists(str) Then
         For Each f As String In IO.Directory.GetFiles(str)
            ScanPath(f)
         Next
      End If
      If IO.File.Exists(str) Then
         Dim ext As String = IO.Path.GetExtension(str.ToLower)
         If ext = ".avi" Or ext = ".wmv" Or ext = ".rmvb" Or ext = ".mpg" Or ext = ".mpeg" Then
            Dim job As New Job(str)
            If Not lstFiles.Items.Contains(job) Then
               lstFiles.Items.Add(job)
            End If
         End If
      End If
   End Sub

   Public Function HasFiles(ByVal str As String) As Boolean
      If IO.Directory.Exists(str) Then
         For Each f As String In IO.Directory.GetFiles(str)
            If HasFiles(f) Then
               Return True
            End If
         Next
      End If
      If IO.File.Exists(str) Then
         Dim ext As String = IO.Path.GetExtension(str.ToLower)
         If ext = ".avi" Or ext = ".wmv" Or ext = ".rmvb" Or ext = ".mpg" Or ext = ".mpeg" Then
            Return True
         End If
      End If
      Return False
   End Function

#End Region

#Region " Loading and saving settings "

   Const params_mpeg4 As String = " -i ""{0}"" -o ""{1}.m4v"" -f mp4 -X 480 -e ffmpeg -q 9 -E faac -R 48 -B 128 -v 0"
   Const params_h264 As String = " -i ""{0}"" -o ""{1}.m4v"" -f mp4 -X 640 -e x264 -q 20 -E faac -R 48 -B 160 -v 0"

   Private Sub MainForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      Select Case My.Settings("mode")
         Case "mpeg4"
            optMPEG4.Checked = True
         Case "h.264"
            optH264.Checked = True
         Case "custom"
            optCustom.Checked = True
            txtCustom.Text = My.Settings("params_custom")
      End Select
      chkTopMost.Checked = CBool(My.Settings("topmost"))
      Me.TopMost = CBool(My.Settings("topmost"))
      Call optCheckedChanged(Nothing, Nothing)

      If Not IsNumeric(My.Settings("window_left")) OrElse CInt(My.Settings("window_left")) < -Me.Width Then
         My.Settings("window_left") = Screen.PrimaryScreen.WorkingArea.Width - Me.Width
      End If
      If Not IsNumeric(My.Settings("window_top")) OrElse CInt(My.Settings("window_top")) < -Me.Height Then
         My.Settings("window_top") = Screen.PrimaryScreen.WorkingArea.Height - Me.Height
      End If

      Me.Left = CInt(My.Settings("window_left"))
      Me.Top = CInt(My.Settings("window_top"))

      FolderBrowserDialog.SelectedPath = My.Settings("target")

      btnStart.Enabled = False
   End Sub

   Private Sub MainForm_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
      If optMPEG4.Checked Then
         My.Settings("mode") = "mpeg4"
      ElseIf optH264.Checked Then
         My.Settings("mode") = "h.264"
      Else
         My.Settings("mode") = "custom"
         My.Settings("params_custom") = txtCustom.Text
      End If
      My.Settings("topmost") = chkTopMost.Checked

      My.Settings("window_left") = Me.Left
      My.Settings("window_top") = Me.Top

      My.Settings("target") = FolderBrowserDialog.SelectedPath
   End Sub

#End Region

#Region " Misc "

   Private Sub lstFiles_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles lstFiles.KeyDown
      If e.KeyCode = Keys.Delete AndAlso lstFiles.SelectedItems.Count > 0 Then
         Dim arr As Object() = Array.CreateInstance(GetType(Object), lstFiles.SelectedItems.Count)
         lstFiles.SelectedItems.CopyTo(arr, 0)
         For Each item As Object In arr
            lstFiles.Items.Remove(item)
         Next
         btnStart.Enabled = lstFiles.Items.Count > 0
      End If
   End Sub

   Private Sub lnkAbout_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkAbout.LinkClicked
      Me.TopMost = False
      Dim a As New AboutBox
      a.ShowDialog()
      If chkTopMost.Checked Then
         Me.TopMost = True
      End If
   End Sub

   Private Sub optCheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optCustom.CheckedChanged, optH264.CheckedChanged, optMPEG4.CheckedChanged
      txtCustom.Enabled = optCustom.Checked
      txtCustom.Visible = optCustom.Checked
      If optH264.Checked Then
         txtCustom.Text = params_h264
      ElseIf optMPEG4.Checked Then
         txtCustom.Text = params_mpeg4
      End If
   End Sub

   Private Sub chkTopMost_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkTopMost.CheckedChanged
      Me.TopMost = chkTopMost.Checked
      If chkTopMost.Checked Then
         Me.Opacity = TOPMOST_OPACITY
      Else
         Me.Opacity = 1
      End If
   End Sub

#End Region
End Class
